//
//  XXImageShowCell.m
//  ppkc2016
//
//  Created by 拼凑的断音 on 16/5/25.
//  Copyright © 2016年 拼凑的断音. All rights reserved.
//

#import "XXImageShowCell.h"
#import "SDWaitingView.h"
#import "XXTool.h"

@interface XXImageShowCell ()<UIScrollViewDelegate,XMLRegionalShowDelegate>

@property (nonatomic,strong) UIScrollView *contentView;

@property (nonatomic,strong) UIImageView *imageView;

/**
 *  加载view
 */
@property (nonatomic,strong) SDWaitingView* loadingView;

@end

@implementation XXImageShowCell
#pragma mark getter
-(UIScrollView*)contentView
{
    if (_contentView==nil)
    {
        _contentView = [[UIScrollView alloc] init];
        _contentView.delegate = self;
        _contentView.showsHorizontalScrollIndicator = NO;
        _contentView.showsVerticalScrollIndicator = NO;
        [self addSubview:_contentView];

        //双击
        UITapGestureRecognizer* doubleTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImage:)];
        doubleTap.numberOfTapsRequired=2;
        [_contentView addGestureRecognizer:doubleTap];
    }
    return _contentView;
}

-(UIImageView*)imageView
{
    if (_imageView==nil)
    {
        _imageView = [[UIImageView alloc] init];
        _imageView.contentMode = UIViewContentModeScaleToFill;
        _imageView.backgroundColor = [UIColor redColor];
        [_contentView addSubview:_imageView];
        
    }
    return _imageView;
}

-(SDWaitingView*)loadingView
{
    if (_loadingView==nil)
    {
        _loadingView = [[SDWaitingView alloc] init];
        _loadingView.hidden = YES;
        _loadingView.mode = SDWaitingViewModePieDiagram;
        [self addSubview:_loadingView];
    }
    return _loadingView;
}

-(void)initUI
{
    self.contentView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width
                                        , [UIScreen mainScreen].bounds.size.height-64);
}

-(void)refreshLayout:(CGRect)frame
{
    self.contentView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
    self.loadingView.frame = CGRectMake((frame.size.width-60)/2
                                        , (frame.size.height-60)/2
                                        , 60
                                        , 60);
}

/**
 *  获取图片尺寸，若尺寸不够，则拉到全屏
 *
 *  @return 尺寸
 */
- (CGSize)convertImageSize
{
    CGSize size=_imageView.image.size;
    if(size.width==0 || size.height==0)
    {
        return CGSizeZero;
    }
    else
    {
        CGSize screenSize=CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64);
        if(size.width<screenSize.width && size.height<screenSize.height)
        {
            CGFloat widthKey=screenSize.width/size.width;
            CGFloat heightKey=screenSize.height/size.height;
            if(widthKey>heightKey)
            {//用高填充
                size.width*=heightKey;
                size.height*=heightKey;
            }
            else
            {//用宽填充
                size.width*=widthKey;
                size.height*=widthKey;
            }
            return size;
        }
        else
        {
            return size;
        }
    }
}


/**
 *  根据图片内容调整大小（初始化调整）
 */
- (void)initToFitContent
{
    //恢复缩放(非常重要)
    [_contentView setZoomScale:1];
    
    //屏幕尺寸
    CGSize screenSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64);
    
    //图片尺寸
    CGSize imageSize=[self convertImageSize];
    
    if(CGSizeEqualToSize(imageSize, CGSizeZero))
    {
        return;
    }
    
    
    //调整图片显示
    _imageView.frame=CGRectMake(0,
                                0,
                                imageSize.width,
                                imageSize.height);
    
    //调整滑动范围
    _contentView.contentSize=CGSizeMake(imageSize.width,imageSize.height);
    
    
    [_contentView setMaximumZoomScale:MAX(1.0, MAX(screenSize.width/imageSize.width, screenSize.height/imageSize.height))];
    [_contentView setMinimumZoomScale:MIN(screenSize.width/imageSize.width, screenSize.height/imageSize.height)];
    [_contentView setZoomScale:_contentView.minimumZoomScale];
    [self scrollViewDidZoom:_contentView];

}

#pragma mark scrollviewDelegate
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGFloat xcenter = scrollView.center.x , ycenter = scrollView.center.y;
    xcenter = scrollView.contentSize.width > scrollView.frame.size.width ? scrollView.contentSize.width/2 : xcenter;
    ycenter = scrollView.contentSize.height > scrollView.frame.size.height ? scrollView.contentSize.height/2 : ycenter;
    
    [_imageView setCenter:CGPointMake(xcenter, ycenter)];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}

#pragma mark click
-(void)tapImage:(UITapGestureRecognizer *)recognizer
{
    if(recognizer.numberOfTapsRequired==2)
    {//放大或缩小
        if(_contentView.zoomScale<(_contentView.maximumZoomScale+_contentView.minimumZoomScale)/2)
        {//放大
            CGPoint touchPoint=[recognizer locationInView:_imageView];
            [_contentView zoomToRect:CGRectMake(touchPoint.x,
                                                touchPoint.y,
                                                0,
                                                0)
                            animated:YES];
        }
        else
        {//缩小
            [_contentView setZoomScale:_contentView.minimumZoomScale animated:YES];
        }
    }
}

#pragma mark api
- (void)loadPhotoModel:(XMLRegionalShow *)model
{
    //清除上一次的delegate
    if(self.model!=nil)
    {
        self.model.delegate=nil;
    }
    self.loadingView.hidden=YES;
    
    //设置本次的delegate
    self.model=model;
    self.model.delegate=self;
    if(self.model.isOrigin)
    {
        [[DKImageSqlite shareImageSqlite] loadImage:self.model.imgUrl
                                        placeHolder:nil
                                             target:nil
                                            process:nil
                                     enableDownload:NO
                                         completion:^(UIImage *imageData) {
                                             if(imageData!=nil)
                                             {
                                                 self.imageView.image=imageData;
                                                 [self initToFitContent];
                                             }
                                             else
                                             {
                                                 self.model.isOrigin=NO;
                                                 [self loadPhotoModel:self.model];
                                             }
                                         }];
    }
    else
    {
        self.loadingView.hidden=NO;
        //self.loadingView.mode=SDWaitingViewModeLoopDiagram;
        [self.loadingView setProgress:self.model.process];
        if(!self.model.isDownload)
        {
            [self.model beginDownload];
        }
        
    }
}

#pragma mark XMLRegionalShowDelegate
-(void)XMLRegionalShow:(XMLRegionalShow *)model didReceiveSize:(long long)receiveSize totalSize:(long long)totalSize image:(UIImage *)image isFinish:(BOOL)isFinish
{
    if(isFinish)
    {
        if(self.model.isOrigin)
        {
            [self.imageView setImage:image];
            [self initToFitContent];
            [self.loadingView setHidden:YES];
        }
        else
        {//下载失败
            [self.loadingView setMode:SDWaitingViewModeError];
        }
    }
    else
    {
        if(totalSize==-1)
        {
            [self.loadingView setProgress:0.01];
        }
        else
        {
            [self.loadingView setProgress:receiveSize*1.0/totalSize];
        }
    }
}


@end
